package com.bpm.example.event.message;

import com.bpm.common.util.FlowableEngineUtil;
import lombok.extern.slf4j.Slf4j;
import org.flowable.engine.repository.ProcessDefinition;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.junit.Before;
import org.junit.Test;

import java.util.List;

/**
 * 消息启动事件
 * 当流程定义中使用了消息启动事件（Message Start Event），
 * 还是可以通过 startProcessInstanceById 或 startProcessInstanceByKey 来启动该流程。
 */
@Slf4j
public class RunMessageStartEventProcessDemo extends FlowableEngineUtil {
    @Before
    public void initFlowableEngineAndServices() {
        //加载Flowable配置文件并初始化流程引擎及服务
        initFlowableEngineAndServices("flowable.cfg.xml");
    }

    @Test
    public void runMessageStartEventProcessDemo() {
        //部署流程
        ProcessDefinition processDefinition = deployResource("processes/message/MessageStartEventProcess.bpmn20.xml");
        //通过API指定消息发起流程
        ProcessInstance processInstance = runtimeService.startProcessInstanceByMessage("dataReportingMessage");
//        ProcessInstance processInstance = runtimeService.startProcessInstanceById(processDefinition.getId()); 测试可以调研启动流程
//        ProcessInstance processInstance = runtimeService.startProcessInstanceByKey(processDefinition.getKey()); 测试可以调研启动流程

        //查询任务
        Task task = taskService.createTaskQuery()
                .processInstanceId(processInstance.getId()).singleResult();
        log.info("当前任务名称为: {}", task.getName());
        //完成任务
        taskService.complete(task.getId());
        //查询消息订阅关系,选择具有 dataReportingMessage 的开始消息事件的单个流程定义
        List<ProcessDefinition> processDefinitionList = repositoryService
                .createProcessDefinitionQuery()
                .messageEventSubscriptionName("dataReportingMessage").list();
        //打印流程定义
        processDefinitionList.forEach((e) -> {
            System.out.println("流程定义ID: " + e.getId());
            System.out.println("流程定义名称: " + e.getName());
            System.out.println("流程定义Key: " + e.getKey());
            System.out.println("流程定义版本: " + e.getVersion());
            System.out.println("流程定义描述: " + e.getDescription());
            System.out.println("流程定义部署ID: " + e.getDeploymentId());
            System.out.println("流程定义资源名称: " + e.getResourceName());
            System.out.println("流程定义分类: " + e.getCategory());
            System.out.println("流程定义是否启动: " + e.isSuspended());
            System.out.println("流程定义是否有图: " + e.hasGraphicalNotation());
        });

    }
}
